/**
 * 文件名: src/components/FileTree.tsx
 * 
 * 文件概述:
 * 文件管理树组件，展示和选择章节，并提供用户信息显示。
 * 与AIDialog集成，支持章节作为参考文件选择。
 * 
 * 依赖项:
 * - 'use client': 声明为客户端组件
 * - react: React核心库
 * - antd: Sider, Menu, Tree, Modal, Button, Avatar, Typography, message组件
 * - ../utils/platform: 获取章节数据和文件选择功能
 * - ../store: 状态管理(章节、选中章节、加载状态)
 * 
 * UI设计:
 * - 左侧边栏: 
 *   - 宽度: 260px，浅灰背景(#f9f9f9)
 *   - 顶部: "New Project" 按钮(粉红色背景，白色文字)
 *   - 分类标题: 大写灰色文字("MY PROJECTS", "CHAPTERS", "CHARACTERS")
 *   - 展开/折叠图标: 右对齐的箭头图标
 * 
 * - 项目列表:
 *   - 彩色图标区分不同项目(方块图标，不同颜色)
 *   - 选中项目显示粉色背景(#ffeaea)
 *   - 项目名称左对齐，黑色文字
 * 
 * - 章节列表:
 *   - 文档图标前缀
 *   - 缩进表示层级关系
 *   - 选中章节显示粉色背景
 * 
 * - 角色列表:
 *   - 人物图标前缀
 *   - 角色名称左对齐
 * 
 * - 底部用户信息:
 *   - 圆形头像
 *   - 用户名: "John Doe"
 *   - 订阅信息: "Free Plan"(灰色小字)
 * 
 * 组件结构:
 * - FileTree: () => JSX.Element
 *   - Spin: 加载状态包装器
 *     - Sider(antd)
 *       - 新建项目按钮("+ New Project")
 *       - 分组标题与折叠控制
 *       - 项目、章节、角色列表
 *       - 底部用户信息(Avatar + Typography)
 *     - Modal(文件选择)
 * 
 * 状态:
 * - 本地状态:
 *   - modalVisible: useState(false) - 模态框显示状态
 *   - expandedKeys: useState<string[]>(['chapters']) - 树展开节点状态
 * - 全局状态(从store获取):
 *   - chapters: 章节列表
 *   - selectedChapter: 当前选中章节
 *   - referenceFiles: 参考文件列表(用于高亮显示)
 *   - isLoading.fileTree: 章节数据加载状态
 * 
 * 副作用:
 * - 组件挂载时: 如果store中没有章节数据，则调用init()加载
 * 
 * 事件处理:
 * - 章节选中: (chapterId) => useAppStore.getState().setSelectedChapter(...)
 * - 添加章节: 创建新章节并添加到列表
 * - 文件选择: 调用platform.showFileSelector()并处理结果
 * - 右键菜单(可选): 提供"添加为参考"选项，调用toggleReferenceFile
 * 
 * 树状数据转换:
 * - 将chapters平面数组转换为Tree组件所需的嵌套结构
 * - 处理章节ID、父子关系等
 * - 为已选参考文件添加特殊图标或样式(如小标记)
 * 
 * 错误处理:
 * - 使用message组件显示加载或操作错误
 * - 加载失败时提供重试选项
 * 
 * 注意事项:
 * - 确保章节选择后立即更新selectedChapter
 * - 处理章节树的展开/折叠状态
 * - 文件选择后需刷新章节列表
 * - 实现章节删除、重命名等管理功能
 * - 提供视觉区分，标识哪些章节被选为参考文件
 */

'use client';

import React, { useState, useEffect, useCallback } from 'react';
import { 
  Layout, 
  Tree, 
  Button, 
  Modal, 
  Spin, 
  Avatar, 
  Typography, 
  message, 
  Menu, 
  Dropdown,
  Empty
} from 'antd';
import type { TreeProps, DataNode } from 'antd/es/tree';
import { 
  FileOutlined, 
  FolderOutlined, 
  UserOutlined, 
  PlusOutlined, 
  DownOutlined, 
  RightOutlined,
  FileAddOutlined,
  ImportOutlined,
  StarOutlined,
  StarFilled,
  MoreOutlined,
  ReloadOutlined,
  EditOutlined,
  DeleteOutlined
} from '@ant-design/icons';
import { useAppStore } from '../store';
import { showFileSelector, getChapters } from '../utils/platform';
import { v4 as uuidv4 } from 'uuid';
import type { Chapter } from '../store';

const { Sider } = Layout;
const { Text, Title } = Typography;
const { DirectoryTree } = Tree;

// 定义类型
interface ChapterTreeNode extends DataNode {
  key: string;
  type?: string;
  chapter?: Chapter;
}

interface ReferenceTagProps {
  selected: boolean;
}

// 自定义章节选择标记组件
const ReferenceTag: React.FC<ReferenceTagProps> = ({ selected }) => {
  return selected ? <StarFilled style={{ color: '#ff6b6b' }} /> : <StarOutlined style={{ color: '#aaa' }} />;
};

// 文件树组件
const FileTree = () => {
  // 本地状态
  const [modalVisible, setModalVisible] = useState(false);
  const [expandedKeys, setExpandedKeys] = useState<string[]>(['chapters']);
  const [contextMenuChapter, setContextMenuChapter] = useState<ChapterTreeNode | null>(null);
  
  // 从store获取全局状态
  const { 
    chapters, 
    selectedChapter, 
    referenceFiles,
    setChapters,
    setSelectedChapter,
    addReferenceFile,
    removeReferenceFile,
    toggleReferenceFile,
    isLoading 
  } = useAppStore();
  
  // 初始化加载
  useEffect(() => {
    if (!chapters || chapters.length === 0) {
      useAppStore.getState().init();
    }
  }, [chapters]);
  
  // 右键菜单处理函数
  const handleRightClick = ({ node, event }: { node: ChapterTreeNode; event: React.MouseEvent }) => {
    event.preventDefault();
    // 只处理章节项
    if (node.type === 'chapter') {
      setContextMenuChapter(node);
    }
  };
  
  // 创建新章节
  const handleAddChapter = () => {
    const newChapter: Chapter = {
      id: uuidv4(),
      title: `新章节 ${chapters ? chapters.length + 1 : 1}`,
      content: '开始编写你的故事...'
    };
    
    const updatedChapters = [...(chapters || []), newChapter];
    setChapters(updatedChapters);
    setSelectedChapter(newChapter);
    
    message.success('已创建新章节');
  };
  
  // 导入文件处理
  const handleImportFile = async () => {
    try {
      setModalVisible(true);
      const result = await showFileSelector();
      setModalVisible(false);
      
      if (result.error) {
        message.error(`导入失败: ${result.error}`);
        return;
      }
      
      if (result.data) {
        message.success(`已选择文件: ${result.data}`);
        // 这里可以添加读取文件内容并添加为章节的逻辑
        // 暂时用占位逻辑
        const newChapter: Chapter = {
          id: uuidv4(),
          title: result.data.split('/').pop() || '导入章节',
          content: '导入的内容...'
        };
        
        setChapters([...(chapters || []), newChapter]);
      }
    } catch (error: unknown) {
      setModalVisible(false);
      const errorMessage = error instanceof Error ? error.message : '未知错误';
      message.error(`操作失败: ${errorMessage}`);
    }
  };
  
  // 刷新章节列表
  const handleRefreshChapters = async () => {
    try {
      const result = await getChapters();
      if (result.error) {
        message.error(`刷新失败: ${result.error}`);
        return;
      }
      
      if (result.data) {
        setChapters(result.data);
        message.success('已刷新章节列表');
      }
    } catch (error: unknown) {
      const errorMessage = error instanceof Error ? error.message : '未知错误';
      message.error(`刷新失败: ${errorMessage}`);
    }
  };
  
  // 树节点选择处理
  const handleSelect: TreeProps['onSelect'] = (selectedKeys, info) => {
    // 使用类型断言来访问node的自定义属性
    const node = info.node as unknown as ChapterTreeNode;
    if (node.type === 'chapter' && selectedKeys.length > 0) {
      const chapterId = selectedKeys[0].toString();
      const selected = chapters.find(chapter => chapter.id === chapterId);
      
      if (selected) {
        setSelectedChapter(selected);
      }
    }
  };
  
  // 添加到参考文件
  const handleAddReference = useCallback((chapter: Chapter) => {
    if (chapter) {
      addReferenceFile(chapter);
      message.success(`已添加"${chapter.title}"到参考文件`);
    }
  }, [addReferenceFile]);
  
  // 从参考文件移除
  const handleRemoveReference = useCallback((chapter: Chapter) => {
    if (chapter) {
      removeReferenceFile(chapter.id);
      message.success(`已从参考文件中移除"${chapter.title}"`);
    }
  }, [removeReferenceFile]);
  
  // 切换参考文件状态
  const handleToggleReference = useCallback((chapter: Chapter) => {
    if (chapter) {
      toggleReferenceFile(chapter.id);
    }
  }, [toggleReferenceFile]);
  
  // 展开/折叠处理
  const handleExpand: TreeProps['onExpand'] = (expandedKeys) => {
    setExpandedKeys(expandedKeys as string[]);
  };
  
  // 构建树数据
  const buildTreeData = useCallback(() => {
    // 基本树结构
    const treeData = [
      {
        title: (
          <div className="tree-category">
            <span>我的项目</span>
          </div>
        ),
        key: 'projects',
        icon: <FolderOutlined />,
        children: [
          {
            title: '我的小说',
            key: 'novel1',
            icon: <FolderOutlined style={{ color: '#ff6b6b' }} />,
            isLeaf: false,
          }
        ]
      },
      {
        title: (
          <div className="tree-category">
            <span>章节</span>
            <Button 
              type="text" 
              size="small" 
              icon={<PlusOutlined />} 
              onClick={handleAddChapter} 
            />
          </div>
        ),
        key: 'chapters',
        icon: <FolderOutlined />,
        children: chapters && chapters.length > 0 ? chapters.map(chapter => {
          // 检查是否为参考文件
          const isReference = referenceFiles && referenceFiles.some(ref => ref.id === chapter.id);
          
          return {
            title: (
              <div className="chapter-item">
                <span className="chapter-title">{chapter.title}</span>
                <ReferenceTag selected={isReference} />
              </div>
            ),
            key: chapter.id,
            icon: <FileOutlined />,
            type: 'chapter',
            isLeaf: true,
            chapter: chapter // 保存章节数据，方便后续使用
          };
        }) : [
          {
            title: '暂无章节',
            key: 'no-chapter',
            icon: null,
            isLeaf: true,
            disabled: true
          }
        ]
      },
      {
        title: (
          <div className="tree-category">
            <span>角色</span>
          </div>
        ),
        key: 'characters',
        icon: <FolderOutlined />,
        children: [
          {
            title: '主角',
            key: 'character1',
            icon: <UserOutlined />,
            isLeaf: true
          }
        ]
      }
    ];
    
    return treeData;
  }, [chapters, referenceFiles, handleAddChapter]);
  
  // 章节右键菜单项
  const contextMenu = (
    <Menu>
      <Menu.Item 
        key="add-reference" 
        icon={<StarOutlined />}
        onClick={() => {
          if (contextMenuChapter) {
            const chapter = chapters.find(c => c.id === contextMenuChapter.key);
            if (chapter) {
              handleAddReference(chapter);
            }
          }
        }}
      >
        添加到参考文件
      </Menu.Item>
      <Menu.Item 
        key="remove-reference" 
        icon={<StarFilled />}
        onClick={() => {
          if (contextMenuChapter) {
            const chapter = chapters.find(c => c.id === contextMenuChapter.key);
            if (chapter) {
              handleRemoveReference(chapter);
            }
          }
        }}
      >
        从参考文件移除
      </Menu.Item>
      <Menu.Divider />
      <Menu.Item key="rename" icon={<EditOutlined />}>
        重命名
      </Menu.Item>
      <Menu.Item key="delete" icon={<DeleteOutlined />} danger>
        删除
      </Menu.Item>
    </Menu>
  );
  
  return (
    <Spin spinning={isLoading?.fileTree} tip="加载中...">
      <div className="file-tree">
        <div className="file-tree-header">
          <Button 
            type="primary" 
            icon={<PlusOutlined />}
            onClick={handleAddChapter}
            style={{ 
              backgroundColor: 'var(--primary-color)',
              marginBottom: 16,
              width: '100%'
            }}
          >
            新建章节
          </Button>
          
          <div className="action-buttons">
            <Button 
              type="text" 
              icon={<ImportOutlined />}
              onClick={handleImportFile}
              title="导入文件"
            />
            <Button 
              type="text" 
              icon={<ReloadOutlined />}
              onClick={handleRefreshChapters}
              title="刷新"
            />
          </div>
        </div>
        
        <Dropdown
          overlay={contextMenu}
          trigger={['contextMenu']}
          visible={contextMenuChapter !== null}
          onVisibleChange={(visible) => {
            if (!visible) setContextMenuChapter(null);
          }}
        >
          <DirectoryTree
            treeData={buildTreeData()}
            defaultExpandedKeys={['chapters']}
            expandedKeys={expandedKeys}
            selectedKeys={selectedChapter ? [selectedChapter.id] : []}
            onSelect={handleSelect}
            onExpand={handleExpand}
            onRightClick={handleRightClick}
            switcherIcon={({ expanded }) => expanded ? <DownOutlined /> : <RightOutlined />}
            showIcon
          />
        </Dropdown>
        
        <div className="user-info">
          <Avatar icon={<UserOutlined />} size={36} />
          <div className="user-details">
            <Text strong>用户名</Text>
            <Text type="secondary" style={{ fontSize: 12 }}>免费版</Text>
          </div>
        </div>
      </div>
      
      <Modal
        title="正在选择文件..."
        visible={modalVisible}
        footer={null}
        closable={false}
      >
        <Spin tip="选择文件中..." />
      </Modal>
      
      <style jsx global>{`
        .file-tree {
          height: 100%;
          display: flex;
          flex-direction: column;
          padding: 16px;
        }
        
        .file-tree-header {
          margin-bottom: 20px;
        }
        
        .action-buttons {
          display: flex;
          justify-content: flex-end;
          margin-bottom: 8px;
        }
        
        .tree-category {
          display: flex;
          justify-content: space-between;
          align-items: center;
          text-transform: uppercase;
          font-size: 12px;
          color: #666;
          font-weight: bold;
        }
        
        .chapter-item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          width: 100%;
        }
        
        .chapter-title {
          flex: 1;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        
        .user-info {
          margin-top: auto;
          padding-top: 16px;
          border-top: 1px solid var(--border-color);
          display: flex;
          align-items: center;
        }
        
        .user-details {
          display: flex;
          flex-direction: column;
          margin-left: 12px;
        }
        
        /* 覆盖Ant Design样式 */
        .ant-tree-node-selected {
          background-color: var(--selected-color) !important;
        }
      `}</style>
    </Spin>
  );
};

export default FileTree;